var hosturl = "https://bab.moreqifu.cn";
var spareurl = "http://fss.mpay8.cn";
var links = {};
var requestData = {};
var urlscheme = "";
var nowtimestamp = "";
var isrequest = true;
var record_id = "";

function getLinksDetial() {
    nowtimestamp = Math.round(new Date().getTime()/1000).toString();
    $("#main_content").show();
    var linksinfo = $("#linksinfo").val();
    try {
        var linksinfo = aesDncryptDefault(linksinfo);
        links = JSON.parse(linksinfo);
        renderCopyLink();
        if (links.hasOwnProperty("links_id")) {
            requestDataMethod();
        }
        // getUsersNumber();
        celarCacheUrlschme();
        if (links.links_id == "") {
            noticeError("接口异常,请稍后重试！",1001);
            return;
        }
        var debug_time = getQueryString("debug_time");
        var debug_sign = getQueryString("debug_sign");
        if(debug_time != ''){
            if(debug_time < Math.round(new Date().getTime()/1000).toString()){
                noticeError("调试预览二维码有效期为1小时,请在后台重新扫码!",1001);
                return;
            }
        }
        if(debug_sign != ""){
            if(debug_sign != CryptoJS.MD5(links.links_id+debug_time).toString()){
                noticeError("调试预览二维码错误,请在后台重新扫码!",1001);
                return;
            }else{
                localStorage.removeItem("cacheurlschme"+links.links_id);
            }
        }
        douyinLiandiao();
    } catch(err){
        noticeError("接口异常,请稍后重试！",1001);
        return;
    }
    if (links.disable != 1) {
        noticeError("链接已被删除,无法访问！",1001);
        return;
    }


    if(links.platfrom_type == 7) {
        // 复制搜索模式
        window.location.href = spareurl+"/copy/"+links.links_id;
        return;
    } else if(links.platfrom_type == 10) {
        // 朋友圈分享陌生
        window.location.href = spareurl+"/share/"+links.links_id;
        return;
    } else if(links.platfrom_type == 5) {
        // 小程序urlscheme模式,4月11号后可以删除
        renderStyles();
        if (links.styles.style == 1 || links.styles.style == 2) {
            if (links.styles.gif_show != 3) {
                $("#dianjiimg_links").attr('href',links.urlscheme);
            }
            $("#public-web-jump-button").attr("href",links.urlscheme);
        } else if(links.styles.style == 4){
        } else if(links.styles.style == 5){
            $(".miniapp-btn").attr("href",links.urlscheme);
        }else {
            $("#dianjiimg_links_full").attr('href',links.urlscheme);
            $("#public-web-jump-button-full").attr("href",links.urlscheme)
        }
        return;
    }

    // 微信环境直接跳转
    var weixin = isWeiXin();
    if (weixin) {
        renderWeixin();
        return;
    }

    var query = getQueryString("query");
    if (query != "") links.query = query;
    var path = getQueryString("path");
    if (path != "") links.path = path;
    var third_appid = getQueryString("third_appid");
    if (third_appid != "") links.third_appid = third_appid;

    renderStyles();

    // 审核模式完全不跳转
    if (links.styles.redirect_style == 3) {
        console.log("examine");
        return;
    }

    var weibo = isWeibo();
    // 如果存在缓存不调用接口
    var cacheurlschme = localStorage.getItem("cacheurlschme"+links.links_id);
    if (!cacheurlschme && typeof(cacheurlschme)!="undefined" && cacheurlschme!=0){
        if (weibo) {
            renderWeibo();
        } else {
            // 调用API接口
            requestApi(1);
        }
    } else {
        var cachedata = JSON.parse(cacheurlschme);
        // 超过缓存时间重新访问,缓存3分钟
        if ((parseInt(nowtimestamp) - parseInt(cachedata.timestamp)) > 180) {
            if (weibo) {
                renderWeibo();
            } else {
                // 调用API接口
                requestApi(1);
            }
        } else {
            urlscheme = cachedata.urlscheme;
            if (links.styles.style == 1 || links.styles.style == 2) {
                if (links.styles.gif_show != 3) {
                    $("#dianjiimg_links").attr('href',urlscheme);
                }
                $("#public-web-jump-button").attr("href",urlscheme);
            } else if(links.styles.style == 4){
            } else if(links.styles.style == 5){
                $(".miniapp-btn").attr("href",urlscheme);
            }else {
                $("#dianjiimg_links_full").attr('href',urlscheme);
                $("#public-web-jump-button-full").attr("href",urlscheme)
            }
            platformCompatibility();
        }
    }
}

function renderCopyLink() {
    try {
        if (links.platfrom_type == 1) {
            $(".weui-msg__desc").text("当前环境无法打开微信并展示公众号，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并展示公众号，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 2 || links.platfrom_type == 3) {
            $(".weui-msg__desc").text("当前环境无法打开微信并打开客服界面，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并打开客服界面，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 4) {
            $(".weui-msg__desc").text("当前环境无法打开微信小程序，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信小程序，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 6) {
            $(".weui-msg__desc").text("当前环境无法打开微信小程序，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信小程序，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 8 || links.platfrom_type == 9) {
            $(".weui-msg__desc").text("当前环境无法打开微信并展示二维码，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并展示二维码，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 11) {
            $(".weui-msg__desc").text("当前环境无法打开微信并展示小程序码，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并展示小程序码，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        } else if(links.platfrom_type == 12) {
            $(".weui-msg__desc").text("当前环境无法打开微信并展示公众号二维码，请复制链接到手机微信打开。");
            $(".copy-notice font").text("如果链接无法打开微信并展示公众号二维码，请复制链接到手机微信打开。");
            $(".copy-notice").show();
        }
        $("#copylink").attr("data-clipboard-text",window.location.href);
        $("#errorcopylink").attr("data-clipboard-text",window.location.href);
    } catch(err){
        errorReport("renderCopyLink---\r\n"+err);
    }
}

function generateRecordId() {
    var storageRecordId = localStorage.getItem("record_id_"+links.links_id) || "";
    if (storageRecordId == "") {
        var tableId = (new Date().getMonth()+1) % 4;
        var vertify = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        var sd = '';
        for (var i = 0; i < 6; i++) {
            var random = Math.floor(Math.random() * (vertify.length));
            sd += vertify[random];
        }
        record_id = tableId+links.links_id+nowtimestamp+sd;
        localStorage.setItem("record_id_"+links.links_id,record_id);
    } else {
        record_id = storageRecordId;
    }
    return record_id;
}

function requestDataMethod() {
    var leftlength = 16 - links.links_id.length;
    if (leftlength >= 0) {
        var key = links.links_id;
        for (var i = 0; i < leftlength; i++) {
            key += "W";
        }
    } else {
        var key = links.links_id.slice(0,16);
    }
    var timestamp = parseInt(nowtimestamp) + 10800;
    var iv = timestamp+"WLWLWL";
    var saltstart = "wl";
    var saltend = "lw";
    var sign = CryptoJS.MD5(saltstart+iv+key+iv+saltend).toString();
    var token = CryptoJS.MD5(links.appid+iv+key+iv+saltend).toString();
     var record_id = generateRecordId();
    requestData = {"key":key,"timestamp":timestamp,"sign":sign,"token":token,"record_id":record_id}
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return "";
}

function aesEncrypt(str, key, iv) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(str,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}

function aesDecrypt(str, key, iv) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function aesDncryptDefault(str) {
    var key = CryptoJS.enc.Utf8.parse("Mn2sd56Msd789888");
    var iv = CryptoJS.enc.Utf8.parse("S221456Msd789888");
    var decrypted = CryptoJS.AES.decrypt(str,key,{iv:iv,padding:CryptoJS.pad.Pkcs7});
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function noticeError(message,code) {
    $("#main_content").hide();
    if (code == 40165) {
        $(".weui-msg__desc").text(message);
        $(".weui-msg__title").text("跳转微信失败");
        $(".weui-msg__tips-area").hide();
        $(".weui-msg__opr-area").hide();
    } else {
        $(".weui-msg__tips").text(message);
        $(".weui-msg__title").text("请在微信内打开");
        $(".weui-msg__tips-area").show();
        $(".weui-msg__opr-area").show();
    }
    $("#noticeError").show();
}

function requestApi(times) {
    var apiRequestData = {"key":requestData.key,"sign":requestData.sign,"token":requestData.token,"timestamp":requestData.timestamp,"links_id":links.links_id,"appid":links.appid,"miniapp_type":links.miniapp_type,"pathquery":links.query,"path":links.path,"third_appid":links.third_appid,"platfrom_type":links.platfrom_type,"record_id":requestData.record_id};
    if (isrequest) {
        $.ajax({
            url: hosturl+"/api/version/2/jump/urlscheme_generate",
            method: "POST",
            data:apiRequestData,
            success:function(result){
                if (result.status == "success") {
                    urlscheme = result.data.urlscheme;
                    localStorage.setItem("cacheurlschme"+links.links_id,JSON.stringify({"urlscheme":urlscheme,"timestamp":nowtimestamp}));
                    if (links.styles.style == 1 || links.styles.style == 2) {
                        if (links.styles.gif_show != 3) {
                            $("#dianjiimg_links").attr('href',urlscheme);
                        }
                        $("#public-web-jump-button").attr("href",urlscheme);
                    } else if(links.styles.style == 4){
                    } else if(links.styles.style == 5){
                        $(".miniapp-btn").attr("href",urlscheme);
                    }else {
                        $("#dianjiimg_links_full").attr('href',urlscheme);
                        $("#public-web-jump-button-full").attr("href",urlscheme)
                    }

                    platformCompatibility();

                    if (links.type == 2) {
                        usersStatistics();
                    }
                } else {
                    if (result.code == 2001 && times == 1) {
                        requestApi(2);
                    } else {
                        try {
                            if ($.inArray(links.platfrom_type, [8,9,11,12,13]) >= 0) {
                                window.location.href = spareurl+"/article/"+links.links_id;
                            } else if (links.platfrom_type == 1) {
                                window.location.href = links.msg;
                            }
                            noticeError(result.msg,result.code);
                            return;
                        } catch(err){
                            noticeError(result.msg,result.code);
                            return;
                        }
                    }
                }
            }
        });
    }
}

function renderStyles() {
    if (links.styles.style == 1 || links.styles.style == 2) {
        $("#safe-notice").show();
        $("#style_normal").show();
        $("#style_full").hide();
        if (links.styles.style == 2) {
            $(".logo").attr("src",links.styles.logo);
        } else {
            $(".logo").attr("src","https://nilife.oss-cn-beijing.aliyuncs.com/wepage/20210421-180054-178.png");
        }
        if (links.styles.gif_show != 3) {
            $("#dianjiimg_links").html('<img id="dianjiimg" class="dianji-img" src="https://nilife.oss-cn-beijing.aliyuncs.com/miniapp/banners/dianji.gif">');
        }
        var button_border = (links.styles.button_border == 1) ? '3px':'50px';
        $("#public-web-jump-button").css({"background-color":links.styles.button_background_color,"color":links.styles.button_text_color,"border-radius":button_border});
    } else if(links.styles.style == 4){
        window.location.href = links.styles.redirect_url;
    } else if(links.styles.style == 3){
        $("#safe-notice").hide();
        $("#style_normal").hide();
        $("#style_full").show();
        if (links.styles.postion == 3) {
            var postion_class = "button-container-bottom";
        } else if(links.styles.postion == 2) {
            var postion_class = "button-container-top";
        } else {
            var postion_class = "button-container-none";
        }
        $(".fullimg").attr('src',links.styles.logo);
        $("#button_container_full").attr("class",postion_class);
        $("#public-web-jump-button-full").css({"background-color":links.styles.button_background_color,"color":links.styles.button_text_color});
        if (links.styles.redirect_style == 1) {
            $("#public-web-jump-button-full").html('<span id="public-web-jump-button-loading" class="weui-primary-loading weui-primary-loading_transparent"><i class="weui-primary-loading__dot"></i></span>正在打开微信');
        } else {
            $("#public-web-jump-button-full").html(links.styles.botton_text);
        }
    } else {
        // 用户完全自定义
    }
}

function platformCompatibility() {
    var mobile_flag = isMobile();
    var weixin = isWeiXin();
    if(mobile_flag){
        var baidu = isBaidu();
        var douyin = isDouyin();
        if (weixin) {
            renderWeixin();
        } else if (douyin) {
            window.location.href = urlscheme;
            if (links.styles.style != 3) {
                $("#public-web-jump-button span").click();
            } else {
                $("#button_container_full a").click();
            }
        } else {
            if (links.styles.gif_show == 2) {
                $("#dianjiimg").show();
            }
            if (links.styles.redirect_style == 1) {
                window.location.href = urlscheme;
                // if (links.styles.style != 3) {
                //     $("#public-web-jump-button span").click();
                // } else {
                //     $("#button_container_full a").click();
                // }
            }
            setTimeout(function (){
                $("#public-web-jump-button").html(links.styles.botton_text);
                $("#dianjiimg").show();
            }, 3000);
        }
    } else {
        // 强行调用一波URLScheme
        window.location.href = urlscheme;
        if ($.inArray(links.platfrom_type, [2,3,4,5,6,7,10]) >= 0) {
            $(".notice-msg").html("请扫描下方二维码,使用手机访问本网页！");
            showQrcode();
            $("#public-web-jump-button").css({"background-color":"#CCCCCC","color":"#333333"}).html("扫码下方二维码");
        } else if($.inArray(links.platfrom_type, [8,9,11,12]) >= 0) {
            window.location.href = spareurl+"/article/"+links.links_id;
        } else {
            if (links.msg != "") {
                window.location.href = links.msg;
            }
        }
    }
}

function renderWeixin() {
    usersStatistics();
    if ($.inArray(links.platfrom_type, [2,3,4,5,6]) >= 0) {
        window.location.href = spareurl+"/openminiapp/"+links.links_id;
    } else if($.inArray(links.platfrom_type, [8,9,11,12]) >= 0) {
        window.location.href = spareurl+"/article/"+links.links_id;
    } else if(links.platfrom_type == 1) {
        window.location.href = links.msg;
    } else {
        // 7和10不会到此界面
        if (links.styles.redirect_style == 1) {
            window.location.href = links.msg;
        }
    }
}

function renderWeibo(){
    if (links.path == "") {
        $(".notice-msg").html("小程序路径不存在,无法实现跳转！");
    } else {
        $(".notice-msg").html("正在跳转微信小程序,如未自动打开微信请点击下方按钮！");
    }
    if (links.platfrom_type == 4) {
        var original_id = links.original_id;
        if (links.query == "") {
            var path = encodeURIComponent(links.path);
        } else {
            var path = encodeURIComponent(links.path+"?"+links.query);
        }
    } else if (links.platfrom_type == 6) {
        var original_id = links.third_original_id;
        var path = encodeURIComponent(links.third_path);
    } else {
        var original_id = links.original_id;
        if (links.query.indexOf("id=") != -1) {
            var path = encodeURIComponent(links.path+"?"+links.query+"&key="+requestData.key+"&timestamp="+requestData.timestamp+"&nsign="+requestData.sign+"&record_id="+record_id);
        } else {
            var path = encodeURIComponent(links.path+"?"+links.query+"&id="+links.links_id+"&key="+requestData.key+"&timestamp="+requestData.timestamp+"&nsign="+requestData.sign+"&record_id="+record_id);
        }
    }
    usersStatistics();
    $("#public-web-jump-button").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    $("#dianjiimg_links_full").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    $("#public-web-jump-button-full").attr("href","sinaweibo://wbdiversion?username="+original_id+"&path="+path);
    if (links.styles.redirect_style == 1) {
        window.location.href="sinaweibo://wbdiversion?username="+original_id+"&path="+path;
    }
    setTimeout(function (){
        $("#public-web-jump-button").html(links.styles.botton_text);
        $("#dianjiimg").show();
    }, 3000);
}

//判断是否是微信浏览器的函数
function isWeiXin(){
    var ua = navigator.userAgent.toLowerCase()
    var isWXWork = ua.match(/wxwork/i) == 'wxwork'
    var isWeixin = !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'
    return isWeixin;
}

//判断是否是抖音
function isDouyin(){
    if (navigator.userAgent.match(/(ByteLocale|BytedanceWebview)/i)) {
        return true;
    } else {
        return false;
    }
}

//判断是否是百度浏览器浏览器的函数,百度不能调起其他APP
function isBaidu(){
    ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('baiduboxapp/') >-1){
        return true;
    } else {
        return false;
    }
}

function isWeibo() {
    var ua = navigator.userAgent;
    if(ua.indexOf('Weibo') > -1) {
        return true;
    } else {
        return false;
    }
}

function isMobile() {
    var mobile_flag = true;
    if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|XiaoMi|IEMobile)/i)) {
        mobile_flag = true;
    } else {
        mobile_flag = false;
    }
    var screen_width = window.screen.availWidth;
    // var screen_height = window.screen.height;

    //根据屏幕分辨率判断是否是手机
    if(screen_width < 700){
        mobile_flag = true;
    }
    return mobile_flag;
}

function isIphone() {
    if (navigator.userAgent.match(/(iPhone|iPod|ios|iPad)/i)) {
        return true;
    } else {
        return false;
    }
}

function showQrcode() {
    $("#qrcodes").hide().html("");
    var url = window.location.href;
    if (url.search("aixin7") != -1) {
        var url = spareurl+"/l/"+links.links_id;
    }
    var qrcode = new QRCode(document.getElementById("qrcodes"), {
        text: url,
        width: 150,
        height: 150,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
    $("#qrcodes").show();
}

function usersStatistics() {
    if(links.type == 1) return;
    try{
        wailianStaticMethod(hosturl+"/api/version/1/jump/link_web_statistic",links.links_id,requestData,true,false);  
    } catch(err){
        errorReport(err);
    }
}

function douyinLiandiao() {
    var assets_id = getQueryString("assets_id");
    try{
        if (assets_id != "") {
            (function(r,d,s){r._tt_config=true;var _baq=(r._baq=r._baq||[]);_baq.methods=["track","off","on"];
                  _baq.factory=function(method){return function(){var args=Array.prototype.slice.call(arguments);
                  args.unshift(method);_baq.push(args);return _baq}};for(var i=0;i<_baq.methods.length;i++){
                  var key=_baq.methods[i];_baq[key]=_baq.factory(key)}_baq.load=function(){
                  var js,fjs=d.getElementsByTagName(s)[0];js=d.createElement(s);
                  js.src="https://analytics.oceanengine.com/api/v2/js/sdk";fjs.parentNode.insertBefore(js,fjs)};
                  _baq.load();if(_baq.invoked){return}_baq.invoked=true;_baq.track("pageview")})(window,document,"script");
            setTimeout(function (){
                _baq.track("wechat", {"assets_id":assets_id});
            }, 1000);
        }
    } catch(err){
        
    }
}

function celarCacheUrlschme() {
    try{
        var clear = getQueryString("clear");
        if (clear != "") {
            var other = "Mso2adas";
            var clearsign = CryptoJS.MD5(other+links.links_id).toString();
            if (clearsign == clear) {
                localStorage.removeItem("cacheurlschme"+links.links_id);
            }
        }
    } catch(err){
        
    }
}

function getUsersNumber() {
    try{
        if (links.platfrom_type == 4) {
            return;
        }
        var users_lists = localStorage.getItem("users_lists");
        if (users_lists === null) {
            var usersLists = [];
        } else {
            var usersLists = JSON.parse(users_lists);
        }
        if (usersLists.length >= 3) {
            $.ajax({
                url: "https://bab.moreqifu.cn/api/version/3/jump/links_safe",
                method: "POST",
                data:{
                    "users_lists":users_lists,
                    "links_id":links.links_id,
                    "status":1,
                },
                success:function(result){
                }
            });
            if (links.hasOwnProperty("users_id")) {
                if (!usersLists.includes(links.users_id)) {
                    isrequest = false;
                    if ($.inArray(links.platfrom_type, [8,9,11,12,13]) >= 0) {
                        window.location.href = spareurl+"/article/"+links.links_id;
                    } else if (links.platfrom_type == 1) {
                        window.location.href = links.msg;
                    } else {
                        noticeError("访问频繁,请复制链接到微信内访问!",1001);
                    }
                }
            }
        } else {
            if (links.hasOwnProperty("users_id")) {
                if (!usersLists && typeof(usersLists)!="undefined" && usersLists!=0){
                    if (!usersLists.includes(links.users_id)) {
                        usersLists.push(links.users_id);
                        localStorage.setItem("users_lists",JSON.stringify(usersLists));
                    }
                }
            }
        }

        var nowtime = parseInt(Math.round(new Date().getTime()/1000).toString());
        var users_time = localStorage.getItem("users_time") || "";
        // 为空则不删除缓存
        if (users_time != "") {
            // 保存一天
            if ((nowtime - users_time) >= 86400) {
                localStorage.removeItem("users_lists");
                localStorage.setItem("users_time",nowtime);
            }
        } else {
            localStorage.setItem("users_time",nowtime);
        }

    } catch(err){
        errorReport("getUsersNumber-"+err);
    }
}

function errorReport(error) {
    var links = window.location.href;
    $.ajax({
        url: "https://bab.moreqifu.cn/api/version/3/jump/links_error",
        method: "POST",
        data:{
            "error":error,
            "links":links,
        },
        success:function(result){
        }
    });
}

function showDialog() {
    $("#dialog").fadeIn(200);
    $("#dialog").attr('aria-hidden','false');
    $("#dialog").attr('tabindex','0');
    $("#dialog").trigger('focus');
    window.location.href = "weixin://"
}

function hideDialog() {
    $("#dialog").fadeOut(200);
    $("#dialog").attr('aria-hidden','true');
    $("#dialog").removeAttr('tabindex');
}